//
//  MyNotificationViewController.m
//  xpkc
//
//  Created by TopSageOSX on 14-8-22.
//  Copyright (c) 2014年 wanmeizty. All rights reserved.
//

#import "MyNotificationViewController.h"

@interface MyNotificationViewController ()

@end

@implementation MyNotificationViewController{
    NSMutableArray *msgArray;
    /**
     *  提示标签
     */
    
    int numid;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        self.navigationItem.title = @"我的消息";
        [self.tabBarItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                 [UIColor colorWithRed:255/255.0f green:159/255.f blue:0/255.f alpha:1], NSForegroundColorAttributeName,
                                                 nil] forState:UIControlStateSelected];
    }
    return self;
}

- (void)viewDidAppear:(BOOL)animated{
    self.navigationController.navigationBar.hidden = NO;
}
- (void)viewDidLoad
{
    self.navigationController.navigationBar.hidden = NO;
    

    [super viewDidLoad];
    if (IsIOS7) {
        self.edgesForExtendedLayout=UIRectEdgeNone;
    }
   
    
    //创建视图
    [self creatTableView];
    //获取通知
    [self getNotification];
}

-(void)creatTableView{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
}
/**
 *  获取通知信息
 */
-(void)getNotification{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"加载中";
    msgArray = [[NSMutableArray alloc]init];
    NSString *module = @"user";
    NSString *interface = @"allmsg";
    NSString *timeString = [GetTime getTime];
    NSString *hashString = [[NSString stringWithFormat:@"%@/%@/key/%@/time/%@",module,interface,KEY,timeString] md5];
    NSString *urlString = [NSString stringWithFormat:@"%@/laravel/public/%@/%@/hash/%@/appid/1",URL2,module,interface,hashString];
    NSDictionary *paramtes = [NSDictionary dictionaryWithObjectsAndKeys:timeString,@"time",[UserMessage sharedUserMessage].userMid,@"userid",@0,@"pagecode",nil];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:urlString parameters:paramtes success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([[dic objectForKey:@"info"] isKindOfClass:[NSString class]]) {
            [self showAlertWithMessage:@"暂无消息"];
            [hud hide:YES];
    }else{
        //获取全部的消息
          NSArray *array = [dic objectForKey:@"info"];
            [msgArray removeAllObjects];
        for (NSDictionary *dic  in array) {
           
            NSString *megID = [NSString stringWithFormat:@"%@",[dic objectForKey:@"id"]];
            numid=[megID intValue];
            NSString *title = [dic objectForKey:@"title"];
            NSString *content = [[dic objectForKey:@"content"]stringByDecodingHTMLEntities];
            NSString *viewLogic = [NSString stringWithFormat:@"%@",[dic objectForKey:@"is_view"]];

            NSDate *date = [NSDate dateWithTimeIntervalSince1970:[[dic objectForKey:@"start_time"]doubleValue]];
            NSString *timeString = [GetTime getYYMMDDHHMMWithDate:date];
            NSDictionary *msgDic = [NSDictionary dictionaryWithObjectsAndKeys:title,@"title",content,@"content",[dic objectForKey:@"start_time"],@"time",timeString,@"timeStr",viewLogic,@"is_view",megID,@"id", nil];
            [msgArray addObject:msgDic];
            //先时间排序
            for (int i = 0; i<msgArray.count; i++) {
                for (int j = 0; j<i; j++) {
                    //FIXME:比较时间进行排序，冒泡或者比较(已完成)
                    NSDictionary *dic1 = [msgArray objectAtIndex:i];
                    double time1 = [[dic1 objectForKey:@"time"]doubleValue];
                    
                    NSDictionary *dic2 = [msgArray objectAtIndex:j];
                    double time2 = [[dic2 objectForKey:@"time"]doubleValue];
                    if (time1>time2) {
                        
                        [msgArray exchangeObjectAtIndex:i withObjectAtIndex:j];
                    }
                }
            }
            //按照未读优先顺序排序
            for (int i = msgArray.count-1; i>=0; i--) {
                NSDictionary *dic = [msgArray objectAtIndex:i];
                int viewed =
                [[dic objectForKey:@"is_view"]intValue];
                if (viewed == 0) {
                    //未读优先
                    [msgArray insertObject:dic atIndex:0];
                    [msgArray removeObjectAtIndex:i];
                }
            }
            
        }
            [hud hide:YES];
        //刷新视图
        [self.tableView reloadData];
            [hud hide:YES];
        }
    
    }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
       

    }];
}
- (void)showAlertWithMessage:(NSString *)message {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:message delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alertView show];
}
#pragma mark - tableview
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (msgArray.count == 0) {
        self.tableView.hidden = YES;
    }else{
        self.tableView.hidden = NO;
    }
    return msgArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 150.0f;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MyNotificationCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[MyNotificationCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    if (msgArray.count>0) {
        NSDictionary *msgDic = [msgArray objectAtIndex:indexPath.row];
        if ([[msgDic objectForKey:@"is_view"]integerValue] == 1) {
            //已读
            cell.read = YES;
        }else{
            cell.read = NO;
        }
        cell.title.text = [msgDic objectForKey:@"title"];
        cell.time.text = [msgDic objectForKey:@"timeStr"];
        cell.content.text = [[msgDic objectForKey:@"content"]stringByConvertingHTMLToPlainText];
    }
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
   
    MyNotificationCell *cell = (MyNotificationCell *)[tableView cellForRowAtIndexPath:indexPath];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    cell.accessoryType=UITableViewCellAccessoryNone;
    cell.read = YES;

    MyNotificationContentViewController *contentVC = [[MyNotificationContentViewController alloc]init];
    contentVC.dic = [msgArray objectAtIndex:indexPath.row];
    NSDictionary *msgDic = [msgArray objectAtIndex:indexPath.row];
        if ([[msgDic objectForKey:@"is_view"]integerValue] == 0) {
            //未读跳转
            [self signNotionsIfRead:[msgDic objectForKey:@"id"]];
        }

    contentVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:contentVC animated:YES];
}
#pragma mark -标记消息为以读
-(void) signNotionsIfRead:(NSString *)messageID{


    NSString *module = @"user";
    NSString *interface = @"readmsg";
    NSString *timeString = [GetTime getTime];
    NSString *hashString = [[NSString stringWithFormat:@"%@/%@/key/%@/time/%@",module,interface,KEY,timeString] md5];
    NSString *url1 = [NSString stringWithFormat:@"%@/laravel/public/%@/%@/hash/%@/appid/1",URL2,module,interface,hashString];
    NSDictionary *paramtes = [NSDictionary dictionaryWithObjectsAndKeys:timeString,@"time",[UserMessage sharedUserMessage].userMid,@"userid",messageID,@"notiid",nil];
    
    //POST请求
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];


    //开始请求
    [manager POST:url1 parameters:paramtes success:^(AFHTTPRequestOperation *operation, id responseObject) {
      
        
        NSLog(@"111");
       
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
       
      
    }];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
   
}


@end
